import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public class ClientHandler implements Runnable {        //类实例化出来时是线程的
    private ServerSocket serverSocket;
    private Server server;

    public ClientHandler(ServerSocket serverSocket,Server server) {     //从外面传进来的
        this.serverSocket = serverSocket;
        this.server = server;
    }

    @Override
    public void run()  {
        while (!Thread.currentThread().isInterrupted()) {   //把这个while再放到一个线程里去
            try (Socket clientSocket = serverSocket.accept();    //等待客户端连接;客户端的Socket；现在代码卡在这一步，在等待客户端连接;监听客户端输入
                 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));  //接收客户端数据流；封装
                 PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {   //发送数据

                String clientIP = clientSocket.getInetAddress().getHostAddress();   //返回IP地址对象；并且将IP地址转成字符显示
                server.appendTextArea("玩家：" + clientIP + " 已连接\n");
                try {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        server.appendTextArea("玩家" + inputLine + "已连接\n");
                        server.onClientConnected();
                        out.println(server.getconnectedClients());
                    }
                } catch (SocketException e) {
                    server.appendTextArea("玩家：" + clientIP + "断开\n");
                }
            }  catch (SocketTimeoutException e) {
                //捕获SocketTimeoutException 异常
                //捕获此异常时检查中断状态
                if (Thread.currentThread().isInterrupted()) {
                    server.appendTextArea("服务器被中断\n");
                    break;
                }
            }   catch (IOException e) {
                server.appendTextArea("服务器IO异常: " + e.getMessage() + "\n");
                break;
            }
        }
    }
}
